import 'package:demo1223/config/httpHead.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'dart:async';
import 'dart:io';
import './httpHeaders.dart';
import '../config/servcie.dart';
import 'package:shared_preferences/shared_preferences.dart';

class DioUtil {
  static Dio dio = Dio();
  
  static Future request(url, {formData}) async {
    Response response;
  
    dio.options.headers = httpHeaderss;

  tokenInter();
    
    try {
      print('开始获取首页数据............................');
      if (formData == null) {
        response = await dio.post(servicePath[url]);
      } else {
        response = await dio.post(servicePath[url], data: formData);
      }
      if (response.statusCode == 200) {
        return response.data;
      } else {
        throw Exception('后端接口出现异常');
      }
    } catch (e) {
      return print('异常=========================={$e}');
    }
  }

  static tokenInter() {
    dio.interceptors
        .add(InterceptorsWrapper(onRequest: (RequestOptions options) {
      dio.lock();
      Future<dynamic> future = Future(() async {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        return prefs.getString("userInfo");
        
      });
      return future.then((val) {
        options.headers["Authorization"] = 'Bearer ${val}';
        return options;
      }).whenComplete((() => dio.unlock()));
    }, onResponse: (Response response) {
      // 在返回响应数据之前做一些预处理
      return response; // continue
    }, onError: (DioError e) {
      // 当请求失败时做一些预处理
      return e; //continue
    }));
  }
}
